import pathlib
import time
import re
import typing
import os
import yaml
import ctypes
import psutil
import subprocess
import requests
import winsound
import datetime
import rich
from selenium.webdriver.edge.webdriver import WebDriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.common.exceptions import *


def print_with_time(*args, **kwargs) -> None:
    """在输出内容前添加当前时间戳，使用rich.print进行格式化输出
    
    功能：在所有输出内容前自动添加当前本地时间，时间格式为YYYY-MM-DD HH:MM:SS
    时间会以蓝色加粗样式显示，其余内容保持rich的默认格式化特性
    
    Args:
        *args: 任意数量的位置参数，将被原样传递给rich.print
        **kwargs: 任意关键字参数，将被原样传递给rich.print
    
    Example:
        >>> print_with_time("系统启动完成")
        [bold blue][2025-08-07 16:45:30][/bold blue] 系统启动完成
        
        >>> print_with_time("操作结果：", "[green]成功[/green]")
        [bold blue][2025-08-07 16:46:10][/bold blue] 操作结果：[green]成功[/green]
    """
    # 获取当前时间并格式化为字符串
    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    # 拼接时间前缀与输出内容并打印
    rich.print(f"[bold blue][{current_time}][/bold blue]", *args, **kwargs)


def On_InputPage_InputLogistics_Day(driver: WebDriver, day: typing.Union[int, str]):
    """设置物流发货时间

    Args:
        driver (WebDriver): WebDriver 实例对象
        day (Union[int, str]): 发货时间，可以是整数（天数）或字符串（如"2天"）
    """
    # 1.展开修改
    xpathvalue = "//div[text()='展开修改']"
    try:
        element = driver.find_element(by=By.XPATH, value=xpathvalue)
        driver.execute_script(
            "arguments[0].scrollIntoView({block: 'center', inline: 'center'});", element)
        try:
            element.click()
        except (ElementClickInterceptedException, ElementNotInteractableException):
            driver.execute_script("arguments[0].click();", element)
    except NoSuchElementException:
        print_with_time(f"提示 : 没有找到展开修改的按钮!因此无需进行点击!")

    # 2.设置是否预售
    if int(day) <= 2:   # 现货模式
        element = driver.find_element(by=By.XPATH,value=f"//*[text()='非预售']")
        try:
            element.click()
        except (ElementClickInterceptedException, ElementNotInteractableException):
            driver.execute_script("arguments[0].click();", element)
    else:
        element = driver.find_element(by=By.XPATH,value=f"//*[text()='时段预售']")
        try:
            element.click()
        except (ElementClickInterceptedException, ElementNotInteractableException):
            driver.execute_script("arguments[0].click();", element)

    # 3.设置发货时间
    if int(day) <= 2:  # 现货模式
        element = driver.find_element(by=By.XPATH, value="//div[text()='48小时发货及揽收']")
        try:
            element.click()
        except (ElementClickInterceptedException, ElementNotInteractableException):
            driver.execute_script("arguments[0].click();", element)
    else:
        element = driver.find_element(by=By.XPATH,value=f"//input[@placeholder='请选择天数']")        
        try:
            element.send_keys(day)
            element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located(locator=(By.XPATH, f"//ul[@role='listbox']/li//*[text()='{day}']")))
            try:
                element.click()
            except (ElementClickInterceptedException, ElementNotInteractableException):
                driver.execute_script("arguments[0].click();", element)
        except TimeoutException:
            print_with_time("提示 : 等待超时，未能找到48小时发货及揽收元素!")




if __name__ == "__main__":
    options = Options()
    options.add_experimental_option("debuggerAddress", "127.0.0.1:9652")
    service = Service()
    driver = WebDriver(options=options, service=service)
    debug_json_data = requests.get(
        url="http://127.0.0.1:9652/json", timeout=5).json()

    # 判断获取回来的数据是否正确
    if not isinstance(debug_json_data, list):
        print_with_time("接口返回数据格式不正确（非列表或为空）")
        exit(0)

    # 过来掉不需要的 page 页面
    filter_json_data = list(
                                    filter(lambda item: (
                                        item['type'] == "page" and
                                        not item['title'].lower().startswith("devtools") and
                                        not item['title'].lower().startswith("offscreen") and
                                        not item['title'].lower().startswith("新标签页") and
                                        not item['url'].lower().startswith("edge://newtab/") and
                                        not item['url'].lower().startswith("chrome-extension") and
                                        not item['url'].lower().startswith("chrome-devtools")
                                    ), debug_json_data)
                                )
    current_activate_handle = filter_json_data[0]['id']
    driver.switch_to.window(current_activate_handle)
    print_with_time(f"Current Url :  {driver.current_url}")
    On_InputPage_InputLogistics(driver)
